package com.design03_behavioral.pattern22_interpreter.example02;


import java.util.Deque;
import java.util.LinkedList;

/**
 * @ClassName 表达式解释器
 * @Description TODO
 * @Author 22963
 * @DATE 2023/9/11 0:34
 */
public class ExpressionInterpreter {

    //Deque双向队列，可以从队列的两端增加或者删除元素
    private Deque<NumExpression> numbers = new LinkedList<>();

    public long interpret(String expression) {

        String[] split = expression.split(" ");
        int length = split.length;

        for (int i = 0; i < (length + 1) / 2; i++) {
            numbers.addFirst(new NumExpression(split[i]));
        }

        for (int i = (length+1)/2; i <length ; i++) {
            String operator = split[i];

            boolean isValid = "+".equals(operator) || "- ".equals(operator)
                    || "*".equals(operator) ||
                    "/".equals(operator);
            if (!isValid) {
                throw new RuntimeException("Expression is invalid: " + expression);
            }

            NumExpression exp1 = numbers.peekFirst();
            NumExpression exp2 = numbers.peekFirst();

            Expression result = null;

            if (operator.equals("+")) {
                result = new PluExpression(exp1,exp2);
            } else if (operator.equals("-")) {
                result = new SubExpression(exp1,exp2);
            } else if (operator.equals("*")) {
                result = new MulExpression(exp1,exp2);
            } else if (operator.equals("/")) {
                result = new DivExpression(exp1,exp2);
            }

            long num = result.interpret();

            numbers.addFirst(new NumExpression(num));
        }

        //运算完成numbers中应该保存着运算结果,否则是无效表达式
        if (numbers.size() != 1) {
            throw new RuntimeException("Expression is invalid: " + expression);
        }
        //移除Deque的第一个元素,并返回
        return numbers.pop().interpret();

    }

}
